﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace System.Data
{
    public class EFUnitOfWork : IUnitOfWork
    {
        private readonly IDbContext _context;
        private bool _disposed;
        private volatile Hashtable _repositories;
        public EFUnitOfWork(IDbContext context)
        {
            _context = context;
        }

        public int SaveChanges()
        {
            throw new NotImplementedException();
        }



        public IRepository<TEntity> Repository<TEntity>() where TEntity : Data.Entity.EntityBase
        {
            if (_repositories == null)
            {
                lock (this)
                {
                    if (_repositories == null)
                    {
                        _repositories = new Hashtable();
                    }
                }
            }

            var type = typeof(TEntity).FullName;

            if (_repositories.ContainsKey(type))
            {
                return (IRepository<TEntity>)_repositories[type];
            }
            var repositoryType = typeof(Repository<>);
            _repositories.Add(type, Activator.CreateInstance(repositoryType.MakeGenericType(typeof(TEntity)), _context));
            return (IRepository<TEntity>)_repositories[type];
        }

        public void BeginTransaction()
        {
            throw new NotImplementedException();
        }

        public int Commit()
        {
            throw new NotImplementedException();
        }

        public void Rollback()
        {
            throw new NotImplementedException();
        }

        public Task<int> SaveChangesAsync()
        {
            throw new NotImplementedException();
        }

        public Task<int> SaveChangesAsync(Threading.CancellationToken cancellationToken)
        {
            throw new NotImplementedException();
        }

        public Task<int> CommitAsync()
        {
            throw new NotImplementedException();
        }

        public void Dispose()
        {
            if (_context.ObjectContext.Connection.State == ConnectionState.Open)
                _context.ObjectContext.Connection.Close();

            Dispose(true);
            GC.SuppressFinalize(this);
        }

        public virtual void Dispose(bool disposing)
        {
            if (!_disposed && disposing)
            {
                _context.Dispose();
            }
            _disposed = true;
        }
    }
}
